package com.example.hzzrpcclient.config.netty;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.bytes.ByteArrayDecoder;
import io.netty.handler.codec.bytes.ByteArrayEncoder;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.ConcurrentHashMap;

/**
 * @author ：hzz
 * @description：TODO
 * @date ：2021/5/18 14:53
 */
@Slf4j
public class NettyMainClient {
    //最初始化的netty连接，只要创建一个就可以
    private  Bootstrap connector = null;

    private ConcurrentHashMap<String,Channel> channelMap=new ConcurrentHashMap<>();

    public Channel connect(String ip,int port){
        String key = ip + ":" + port;
        Channel channel=null;
        if(channelMap.containsKey(key)){
             channel = channelMap.get(key);
        }
        if(channel==null||!channel.isActive()){
            System.out.println("netty断开链接");
            ChannelFuture connect = null;
            try {
                connect = connector.connect(ip, port).sync();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            connect.awaitUninterruptibly(3000);
            channel = connect.channel();
            channelMap.put(key,channel);
        }
        return channel;
    }

    private int nettyWorkThreadcn = 10;

    //初始化netty的连接池
    public void getclients() {
        EventLoopGroup group = new NioEventLoopGroup(nettyWorkThreadcn);
        connector = new Bootstrap();
        connector.group(group)
                .channel(NioSocketChannel.class)
                .option(ChannelOption.TCP_NODELAY, true)
                .handler(
                        new ChannelInitializer<SocketChannel>() {
                            @Override
                            public void initChannel(SocketChannel ch) throws Exception {
                                ChannelPipeline p = ch.pipeline();

                                p.addLast("encoder", new ByteArrayEncoder());
                                p.addLast("decoder", new ByteArrayDecoder());
                                p.addLast(new LoggingHandler(LogLevel.INFO));
                                p.addLast(new NettyClientHandler());
                            }
                        });
    }


    private WriteEndChannelFutureListener writeListener = new WriteEndChannelFutureListener();

    private class WriteEndChannelFutureListener implements ChannelFutureListener {
        private WriteEndChannelFutureListener() {
        }

        @Override
        public void operationComplete(ChannelFuture future) throws Exception {
            log.debug("------netty send ----" + future.isDone());
        }
    }




}
